﻿using Newtonsoft.Json;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using RabbitMQDemo.DelayQueue.Shared;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.DependencyInjection;

namespace RabbitMQDemo.DelayQueue.Consumer02
{
    public class MessageConsumer02Service : ITransientDependency
    {
        public void  Run()
        {
            using (var connection = new ConnectionFactory().CreateConnection())
            {
                using (var channel = connection.CreateModel())
                {
                    //string queueName = "zzhellodelay10s";
                    //channel.QueueDeclare(queue: queueName, durable: true, exclusive: false, autoDelete: false, arguments: null);

                    string exchangeName = "exchange-direct-delay20s";
                    channel.ExchangeDeclare(exchange: exchangeName, type: "direct");

                    string name = channel.QueueDeclare().QueueName;
                    channel.QueueBind(queue: name, exchange: exchangeName, routingKey: "routing-delay-delay20s");

                    //channel.QueueBind(queue: queueName, exchange: exchangeName, routingKey: "routing-delay-delay10s");

                    //回调，当consumer收到消息后会执行该函数
                    var consumer = new EventingBasicConsumer(channel);
                    consumer.Received += (model, ea) =>
                    {
                        var body = ea.Body;
                        var message = Encoding.UTF8.GetString(body.ToArray());
                        MessageEntity messageEntity = JsonConvert.DeserializeObject<MessageEntity>(message);
                        Console.WriteLine(" Consumer02 Received message:{0},time:{1}", messageEntity.Body, DateTime.Now);
                    };

                    channel.BasicConsume(queue: name,
                               autoAck: true,
                               consumer: consumer);

                    Console.WriteLine(" Press [enter] to exit.");
                    Console.ReadLine();
                }
            }
        }

        
    }
}
